package git.bds.nyc.communal.service.agreement;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.yulichang.base.MPJBaseServiceImpl;
import git.bds.nyc.communal.convert.AgreementConvert;
import git.bds.nyc.communal.mapper.mp.AgreementMapper;
import git.bds.nyc.communal.model.domain.Agreement;
import git.bds.nyc.communal.model.dto.AgreementDTO;
import git.bds.nyc.exception.BusinessException;
import git.bds.nyc.framework.file.minio.MinioConfig;
import git.bds.nyc.framework.file.minio.MinioUtil;
import git.bds.nyc.framework.redis.constant.RedisConstants;
import git.bds.nyc.result.ResultCode;
import lombok.SneakyThrows;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 成大事
 * @since 2023-06-07 20:14:13
 */
@Service
public class AgreementServiceImpl extends MPJBaseServiceImpl<AgreementMapper, Agreement> implements AgreementService {

    @Resource
    private MinioUtil minioUtil;

    @Resource
    private MinioConfig minioConfig;

    /**
     * 创建协议
     *
     * @param agreementDTO 协议dto
     * @return {@link Boolean}
     */
    @Override
    @SneakyThrows
    public Boolean createAgreement(AgreementDTO agreementDTO) {
        String agreementPath = minioUtil.uploadAgreement(minioConfig.getBucketName(), agreementDTO.getFile());
        Agreement agreement = AgreementConvert.INSTANCE.toAgreement(agreementDTO);
        agreement.setPath(agreementPath);
        try {
            this.baseMapper.insert(agreement);
        } catch (Exception e){
            minioUtil.removeFile(minioConfig.getBucketName(),agreementPath);
        }
        return true;
    }

    /**
     * 删除协议
     *
     * @param id 身份证
     * @return {@link Boolean}
     */
    @Override
    @CacheEvict(value = RedisConstants.REDIS_AGREEMENT_KEY)
    public Boolean delAgreement(Long id) {
        Agreement agreement = baseMapper.selectOne(new LambdaQueryWrapper<Agreement>()
                .select(Agreement::getPath)
                .eq(Agreement::getId,id));
        if(agreement == null){
            throw new BusinessException(ResultCode.NOT_EXIST.getCode(),ResultCode.NOT_EXIST.getMessage());
        }
        return minioUtil.removeFile(minioConfig.getBucketName(),agreement.getPath()) && baseMapper.deleteById(id) > 0;
    }

}
